<?php


namespace app\index\controller\wanlshop;


use app\common\controller\Wanlshop;
use app\common\library\Auth;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class User extends Wanlshop
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
    protected $groupList = [];

    /**
     * Shopsort模型对象
     * @var \app\index\model\wanlshop\Shopsort
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('app\admin\model\User');
        $this->groupList = \app\admin\model\UserGroup::column('id,name');
        $this->groupList[0] = '无';
        ksort($this->groupList);
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $extends = [
                //'parent_id' => $params['parent_id'],
                'group_id' => $params['group_id'],
                'nickname' => $params['nickname'],
                'avatar' => $params['avatar'],
                'shop_id' => $this->shop->id,
            ];
            $auth = Auth::instance();
            $result = $auth->register($params['username'], $params['password'], '', $params['mobile'], $extends);
            if ($result == true) {
                $this->success();
            } else {
                $this->error(__('No rows were inserted'));
            }
        }
        $this->view->assign('groupList', build_select('row[group_id]', $this->groupList, '', ['class' => 'form-control selectpicker']));
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['shop_id'] != $this->shop->id) {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign('groupList', build_select('row[group_id]', $this->groupList, $row['group_id'], ['class' => 'form-control selectpicker']));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    // 充值
    public function recharge($ids){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }



        if($this->request->isPost()){
            $money = $this->request->post('money');
            $shop_money = $this->auth->getUser()['money'];

            if(($shop_money-$money)<0){
                $this->error(__('余额不够!'));
            }

            controller('addons\wanlshop\library\WanlPay\WanlPay')->money($money, $ids, '商家增加用户余额', 'recharge', '');
            controller('addons\wanlshop\library\WanlPay\WanlPay')->money(-$money, $this->auth->id, '商家增加用户余额', 'recharge', '');
            $this->success();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}